/**
 * Created by L.jp
 * Description:
 * User: 86189
 * Date: 2021-10-12
 * Time: 22:58
 */
class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode() {}
      TreeNode(int val) { this.val = val; }
      TreeNode(int val, TreeNode left, TreeNode right) {
          this.val = val;
          this.left = left;
          this.right = right;
      }
}
public class BinaryTree {
    public int preIndex=0;
    public TreeNode buildTreeChild(int[] preorder, int[] inorder,int inbegin,int inend) {
        if(inbegin>inend){
            return null;
        }
        TreeNode root=new TreeNode(preorder[preIndex]);
        //找到位置
        int rootIndex=findInorderIndex(inorder,inbegin,inend,preorder[preIndex]);
        preIndex++;
        root.left=buildTreeChild(preorder,inorder,inbegin,rootIndex-1);
        root.right=buildTreeChild(preorder,inorder,rootIndex+1,inend);
        return root;
    }
    public int findInorderIndex(int[]inorder,int inbegin,int inend,int key){
        for(int i=inbegin;i<=inend;i++){
            if(inorder[i]==key){
                return i;
            }
        }
        return -1;
    }
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if(preorder==null || inorder==null){
            return null;
        }
        return buildTreeChild(preorder,inorder,0,inorder.length-1);
    }
}